<template>
  <Container class="brand-list">
    <div slot="header" style="height:140px" class="container-header large">
      <Form class="search">
        <Row>
          <i-col span="6">
            <FormItem label="经销商">
              <DistributorSelect v-model="list.form.distributorId" />
            </FormItem>
            <FormItem label="单号">
              <Input v-model="list.form.purchOrderSn" class="storeNmae" clearable placeholder="请输入单号" />
            </FormItem>
            <FormItem label="活动类型">
              <Select v-model="list.form.factoryTagIds" clearable filterable @on-change="onSearchBtnClick">
                <Option v-for="(item, index) in factoryTagList" :key="index" :value="item.id">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="5">
            <FormItem label="门店">
              <StoreSelect v-model="list.form.storeId" :src="src" />
            </FormItem>
            <FormItem label="商品品牌">
              <SelectList v-model="list.form.brandId" list-type="selfList" :self-list="brandList" />
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem label="订单时间">
              <DatePicker v-model="list.form.date" :clearable="true" format="yyyy-MM-dd" type="daterange" placement="bottom-start" placeholder="选择日期" />
            </FormItem>
            <FormItem label="商品名称">
              <GoodSelect v-model="list.form.productIds" />
            </FormItem>
          </i-col>
          <i-col span="5">
            <FormItem label="条码">
              <Input v-model="list.form.barcode" class="storeNmae" clearable placeholder="请输入条码" />
            </FormItem>
            <FormItem label="门店维护人">
              <SupplierSalesman v-model="list.form.salesmanSalesId" />
            </FormItem>
          </i-col>
          <i-col class-name="search" span="2">
            <Button
              class="btn-search large"
              type="primary"
              icon="ios-search"
              @click="onSearchBtnClick"
            />
          </i-col>
        </Row>
      </Form>
    </div>
    <Tabs v-model="tab">
      <div slot="extra" class="item">
        小计:共<span class="font-red">{{ total }}</span>条记录, 单据订货:<span class="font-red">{{ retainQuantity }}</span> 单据发货:<span class="font-red">{{ shipQuantity }}</span> 单据排单:<span class="font-red">{{ singleRowQuantity }}</span> 扫码入库:<span class="font-red">{{ matchQuantity }}</span>
      </div>
      <export-btn @onExport="onExport" class="item" slot="extra"></export-btn>
      <TabPane label="发货统计报表" name="tab1">
        <Table
          :height="options.tableHeight"
          stripe
          :columns="list.columns"
          :data="list.data"
          no-data-text="亲，没有找到相关记录哦！~"
        />
        <div class="pager">
          <Page
            :total="list.totalItem"
            :current="list.currentPage"
            :page-size="list.pageSize"
            show-sizer
            placement="top"
            @on-change="onPageChange"
            @on-page-size-change="onPageSizeChange"
          />
        </div>
        <Loader :status="list.status" @refresh="getData" />
      </TabPane>
    </Tabs>
    <BillItem ref="billModal" @success="getData" />
    <WarehouseIteml ref="warehouseModal" @success="getData" />
    <ShipItem ref="shipModal" @success="getData" />
  </Container>
</template>
<script>
import table from '@/table'
import { mapGetters } from 'vuex'
import ShipListData from './list/ShipListData'
import DistributorSelect from '@/components/DistributorSelect'
import StoreSelect from '@/components/StoreSelect'
import SupplierSalesman from '@/components/SupplierSalesman'
import GoodSelect from '@/components/GoodSelect'
import BillItem from './edit/BillItem'
import WarehouseIteml from './edit/WarehouseIteml'
import SelectList from '@/components/SelectList'
import { clearEmpty, formatDate } from '@/util'
export default {
  name: 'report/ship/shipList',
  components: {
    DistributorSelect,
    StoreSelect,
    SupplierSalesman,
    GoodSelect,
    SelectList,
    BillItem,
    WarehouseIteml
  },
  data () {
    return {
      tab: 'tab1',
      list: ShipListData,
      options: {
        tableHeight: 300
      },
      src: '/common/store/listStores',
      brandList: [],
      matchQuantity: '',
      retainQuantity: '',
      shipQuantity: '',
      singleRowQuantity: '',
      total: ''
    }
  },
  mounted () {
    this.list.currentPage = ~~this.$route.query.currentPage || 1
    this.list.pageSize = ~~this.$route.query.pageSize || this.list.pageSize
    this.$store.dispatch('getfactoryTag')
    this.initTable()
    this.getData()
    this.getBrand()
    this.$bus.$on('onOpenSn', ({ item }) => this.onOpenSn(item))
    this.$bus.$on('onOpenNum', ({ item }) => this.onOpenNum(item))
  },
  destroyed () {
    this.$bus.$off()
  },
  computed: {
    ...mapGetters([
      'factoryTag'
    ]),
    factoryTagList () {
      let list = []
      let allArr = []
      allArr = (this.factoryTag || []).map(item => {
        return item.id
      })
      allArr.push('-1')
      let newArr = []
      newArr = JSON.stringify(allArr).replace(/\[|\{|\]|\}/g, '')
      list.unshift({
        id: newArr,
        label: '全部活动'
      }, {
        id: '-1',
        label: '不参与活动'
      })
      return list.concat(this.factoryTag)
    }
  },
  methods: {
    ...table,
    funArr (arr) {
      let newsArr = []
      for (let i = 0; i < arr.length; i++) {
        if (newsArr.indexOf(arr[i]) === -1) {
          newsArr.push(arr[i])
        }
      }
      return newsArr
    },
    onSearchBtnClick () {
      this.list.currentPage = 1
      this.getData()
    },
    getBrand () {
      this.$ajaxGet('product/common/supplier_brand').then(res => {
        this.brandList = res.map(item => {
          item.value = item.brandId
          item.text = item.brandName
          return item
        })
      })
    },
    getData () {
      this.list.status = 'loading'
      let v = this.formatParam();
      if (!v) return
      let param = {
        ...this.formatParam(),
        current: this.list.currentPage,
        size: this.list.pageSize
      }
      this.$jsonPost('/report/product_shipment_statistic/page', param).then(data => {
        this.list.data = []
        this.list.totalItem = Number(data.total)
        this.list.data = data.records || []
        if (this.list.currentPage == 1) {
          this.retainQuantity = data.reportStatistics.retainQuantity
          this.shipQuantity = data.reportStatistics.shipQuantity
          this.singleRowQuantity = data.reportStatistics.singleRowQuantity
          this.matchQuantity = data.reportStatistics.matchQuantity
          this.total = data.reportStatistics.total
        }
        this.list.status = 'pass'
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    formatParam() {
      let text = ''
      if (!this.list.form.date[0] || !this.list.form.date[1] || !this.list.form.date.length) {
        text = '请选择导出日期'
      } else if ((new Date(this.list.form.date[1]) - new Date(this.list.form.date[0])) / (1000 * 60 * 60 * 24) > 91) {
        text = '导出时间间隔不得超过90天'
      }
      if (text) {
        this.$Notice.info({
          title: text
        })
        this.list.status = 'pass'
        return
      }
      let param = {
        purchOrderSn: this.list.form.purchOrderSn,
        distributorId: this.list.form.distributorId,
        storeId: this.list.form.storeId,
        barcode: this.list.form.barcode,
        brandId: this.list.form.brandId,
        productIds: this.list.form.productIds ? this.list.form.productIds.split(',') : null,
        salesmanSalesId: this.list.form.salesmanSalesId,
        factoryTagIds: this.list.form.factoryTagIds,
        needStatistics: false // 导出不带小计
      }
      if (param.factoryTagIds) {
        if (param.factoryTagIds.length > 1) {
          let arr = this.funArr(param.factoryTagIds.toString().split('"')).filter(s => {
            // return s && s.trim() && s !== ','
            return s !== ',' && s.trim()
          })
          if (param.factoryTagIds === '-1') {
            param.factoryTagIds = []
            param.mustFactory = false
          } else {
            let newArr = arr.filter(i => {
              return i !== '-1'
            })
            param.factoryTagIds = newArr
            param.mustFactory = true
          }
        } else {
          param.factoryTagIds = param.factoryTagIds.length === 0 ? [] : [param.factoryTagIds]
        }
      }
      if (this.list.form.date[0] && this.list.form.date[1] && this.list.form.date.length) {
        param.startReportDate = formatDate(this.list.form.date[0]) + ' 00:00:00'
        param.endReportDate = formatDate(this.list.form.date[1]) + ' 23:59:59'
      }
      param = clearEmpty(param)
      return param
    },
    onExport () {
      this.list.status = 'loading'
      let v = this.formatParam();
      if (!v) return
      let param = {
        ...this.formatParam()
      }
      this.$jsonPost('/report/product_shipment_statistic/excel_export', param).then(res => {
        this.list.status = 'pass'
        this.$Modal.success({
          title: '导出成功',
          content: '请到首页-导出列表处下载',
          onOk: () => {
            this.$router.push('/home/export/list')
          }
        })
      }).catch(() => {
        this.list.status = 'pass'
      })
    },
    onPageChange (number) {
      this.list.currentPage = number
      this.$router.push({
        name: 'report/ship/shipList',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
      this.getData()
    },
    onPageSizeChange (pageSize) {
      this.list.currentPage = 1
      this.list.pageSize = pageSize
      this.$router.push({
        name: 'report/ship/shipList',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
      this.getData()
    },
    onOpenSn (item) {
      this.$refs.billModal.open(item)
    },
    onOpenNum (item) {
      this.$refs.warehouseModal.open(item)
    }
  },
  watch: {
    $route () {
      let page = ~~this.$route.query.currentPage
      let table = this.list
      if (table.currentPage !== page) {
        table.currentPage =
          ~~this.$route.query.currentPage === 0
            ? 1
            : ~~this.$route.query.currentPage
        this.getData()
      }
    }
  }
}
</script>
